package com.xinheyun.demo.leetcode;

/**
 * @description: TODO
 * @author: Sarah
 * @modified By: Sarah
 * @date: Created in 2021/8/10 20:44
 * @version:v1.0
 */
public class test413 {

    public static void main(String[] args) {
        Solution003 solutio01 = new Solution003();
        int[] nums = {1,2,3,4,5};
        System.out.println(solutio01.numberOfArithmeticSlices(nums));

    }
}

class Solutio01 {

    public int numberOfArithmeticSlices(int[] nums) {
        if (nums.length < 3) {
            return 0;
        }
        int res = 0, sum = 0;
        int cha = nums[1] - nums[0];
        for (int i = 2; i < nums.length; i++) {
            if (cha == nums[i] - nums[i - 1]) {
                sum++;
            } else {
                if (sum >= 2) {
                    res++;
                    for (int j = 1; j <= sum - 2; j++) {
                        int dividend = 1;
                        int divisor = 1;
                        for(int k=0;k<j;k++){
                            dividend=dividend*(sum+1-k);
                            divisor = divisor*(k+1);
                        }
                        res+=dividend/divisor;
                    }
                }
                sum = 0;
            }
        }
        return res;


    }
}

class Solution003 {
    public int numberOfArithmeticSlices(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return 0;
        }
//d:差数
        int d = nums[0] - nums[1], t = 0;
        int ans = 0;


        //如果相同则t++,否则重新计算d,重置t为0，每次ans都加t
        // 因为等差数列的长度至少为 3，所以可以从 i=2 开始枚举
        for (int i = 2; i < n; ++i) {
            if (nums[i - 1] - nums[i] == d) {
                ++t;
            } else {
                d = nums[i - 1] - nums[i];
                t = 0;
            }
            ans += t;
        }
        return ans;
    }
}

